package com.wewins.fota.service;

import com.alibaba.fastjson.JSONObject;
import com.wewins.fota.bean.bo.FotaServer;
import com.wewins.fota.bean.dto.FotaServerResp;
import com.wewins.fota.common.constant.RedisConst;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class FotaServerService {
    private final RedisTemplate<String, String> template;

    public FotaServerService(RedisTemplate<String, String> template) {
        this.template = template;
    }

    public FotaServerResp queryAll() {
        FotaServerResp build = FotaServerResp.builder().servers(new ArrayList<>()).build();
        Set<String> keys = template.keys(RedisConst.REDIS_KEY_SERVER_INFOS);
        if (keys != null && keys.size() > 0) {
            List<FotaServer> list = keys.stream()
                    .map(item -> JSONObject.parseObject(template.opsForValue().get(item), FotaServer.class))
                    .collect(Collectors.toList());
            build.setServers(list);
        }
        return build;
    }

    public FotaServer queryByDomain(String domain) {
        Set<String> keys = template.keys(RedisConst.REDIS_KEY_SERVER_INFOS);
        if (keys != null && keys.size() > 0) {
            for (String key : keys) {
                FotaServer fotaServer = JSONObject.parseObject(template.opsForValue().get(key), FotaServer.class);
                if (fotaServer != null && domain.equals(fotaServer.getDomain())) {
                    return fotaServer;
                }
            }
        }
        return null;
    }
}
